﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Calculator
{
    public partial class Form1 : Form
    {
        private string currentExpression = "";
        private bool newOperation = true;
        private double lastResult = 0;
        public Form1()
        {
            InitializeComponent();
        }
        private void ButtonClickHandler(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            string input = btn.Text;

            switch (input)
            {
                case "AC":
                    currentExpression = "";
                    txtDisplay.Text = "";
                    newOperation = true;
                    lastResult = 0;
                    break;

                case "=":
                    CalculateResult();
                    newOperation = true;
                    break;

                default:
                    if (newOperation)
                    {
                        // 如果是运算符且处于新操作状态，继承上次结果
                        if ("+-*/".Contains(input))
                        {
                            currentExpression = lastResult.ToString();
                            newOperation = false;
                        }
                        else
                        {
                            currentExpression = "";
                            newOperation = false;
                        }
                    }

                    if ("+-*/".Contains(input) && currentExpression.EndsWith(input))
                        return;

                    currentExpression += input;
                    txtDisplay.Text = currentExpression;
                    break;
            }
        }
        private void CalculateResult()
        {
            try
            {
                DataTable table = new DataTable();
                lastResult = Convert.ToDouble(table.Compute(currentExpression, ""));
                txtDisplay.Text = $"{currentExpression}={lastResult}";
                currentExpression = lastResult.ToString();
            }
            catch (DivideByZeroException)
            {
                MessageBox.Show("不能除以零！");
                currentExpression = "";
                txtDisplay.Text = "";
            }
            catch (Exception)
            {
                MessageBox.Show("无效的表达式！");
                currentExpression = "";
                txtDisplay.Text = "";
            }
        }
    }
}
